<template>
  <n-form ref="formRef" :model="formValue" :rules="rules" label-placement="left" label-width="auto" require-mark-placement="right-hanging" :disabled="isSubmitting">
    <n-grid :cols="24" :x-gap="24">
      <n-form-item-gi :span="12" label="姓名" path="name">
        <n-input v-model:value="formValue.name" placeholder="请输入姓名" />
      </n-form-item-gi>
      <n-form-item-gi :span="12" label="性别" path="gender">
        <n-select
          v-model:value="formValue.gender"
          placeholder="请选择性别"
          :options="genderOptions"
        />
      </n-form-item-gi>
      <n-form-item-gi :span="12" label="出生年月" path="birthDate">
        <n-date-picker v-model:value="formValue.birthDate" type="date" placeholder="请选择出生年月" class="w-full" />
      </n-form-item-gi>
      <n-form-item-gi :span="12" label="籍贯" path="nativePlace">
        <n-input v-model:value="formValue.nativePlace" placeholder="请输入籍贯" />
      </n-form-item-gi>
      <n-form-item-gi :span="12" label="级别" path="level">
        <n-select
          v-model:value="formValue.level"
          placeholder="请选择级别"
          :options="levelOptions"
        />
      </n-form-item-gi>
      <n-form-item-gi :span="12" label="职务" path="position">
        <n-input v-model:value="formValue.position" placeholder="请输入职务" />
      </n-form-item-gi>
      <n-form-item-gi :span="12" label="干部类型" path="cadreType">
        <n-select
          v-model:value="formValue.cadreType"
          placeholder="请选择干部类型"
          :options="cadreTypeOptions"
        />
      </n-form-item-gi>
      
      <n-form-item-gi :span="12" label="单位归属" path="unitId">
        <n-select
          v-model:value="formValue.unitId"
          filterable
          placeholder="请选择单位归属"
          :options="unitSelectOptions"
          :loading="unitStore.loading"
          clearable
        />
      </n-form-item-gi>

      <n-form-item-gi :span="12" label="最高学历" path="highestEducation">
        <n-select
          v-model:value="formValue.highestEducation"
          placeholder="请选择最高学历"
          :options="educationOptions"
        />
      </n-form-item-gi>
      <n-form-item-gi :span="12" label="最高学位" path="highestDegree">
        <n-select
          v-model:value="formValue.highestDegree"
          placeholder="请选择最高学位"
          :options="degreeOptions"
        />
      </n-form-item-gi>
      <n-form-item-gi :span="24" label="熟悉专长" path="expertise">
        <n-input
          v-model:value="formValue.expertise"
          type="textarea"
          placeholder="请输入熟悉专长"
          :autosize="{ minRows: 2 }"
        />
      </n-form-item-gi>
      <n-form-item-gi :span="24" label="拟授课方向" path="proposedTeachingDirections">
        <n-select
          v-model:value="formValue.proposedTeachingDirections"
          multiple
          filterable
          placeholder="请选择拟授课方向 (最多选2个)"
          :options="teachingDirectionOptions"
          :max-tag-count="2" 
        />
      </n-form-item-gi>

      <n-form-item-gi :span="8" label="意向授课高校1" path="intendedUniversity1">
        <n-select
          v-model:value="formValue.intendedUniversity1"
          filterable
          placeholder="请选择意向授课高校1"
          :options="universitySelectOptions"
          :loading="universityStore.loading"
          clearable
        />
      </n-form-item-gi>
      <n-form-item-gi :span="8" label="意向授课高校2" path="intendedUniversity2">
        <n-select
          v-model:value="formValue.intendedUniversity2"
          filterable
          placeholder="请选择意向授课高校2 (可选)"
          :options="universitySelectOptions"
          :loading="universityStore.loading"
          clearable
        />
      </n-form-item-gi>
      <n-form-item-gi :span="8" label="意向授课高校3" path="intendedUniversity3">
        <n-select
          v-model:value="formValue.intendedUniversity3"
          filterable
          placeholder="请选择意向授课高校3 (可选)"
          :options="universitySelectOptions"
          :loading="universityStore.loading"
          clearable
        />
      </n-form-item-gi>

      <n-form-item-gi :span="24" label="人事变动" path="personnelChanges">
        <n-input
          v-model:value="formValue.personnelChanges"
          type="textarea"
          placeholder="请输入人事变动情况"
          :autosize="{ minRows: 2 }"
        />
      </n-form-item-gi>
      <n-form-item-gi :span="24" label="备注" path="remarks">
        <n-input
          v-model:value="formValue.remarks"
          type="textarea"
          placeholder="请输入备注信息"
          :autosize="{ minRows: 2 }"
        />
      </n-form-item-gi>
    </n-grid>
    <div class="flex justify-between mt-6">
      <div>
        <n-button v-if="!initialData" @click="generateMockData" type="info" ghost>
          🎲 一键生成虚拟信息
        </n-button>
      </div>
      <div>
        <n-button @click="handleCancel" :disabled="isSubmitting" class="mr-4">取消</n-button>
        <n-button type="primary" @click="handleValidateAndSubmit" :loading="isSubmitting" :disabled="isSubmitting">
          {{ initialData ? '保存更新' : '创建' }}
        </n-button>
      </div>
    </div>
  </n-form>
</template>

<script setup>
import { ref, watch, computed, onMounted } from 'vue';
import {
  NForm,
  NFormItemGi,
  NInput,
  NSelect,
  NDatePicker,
  NButton,
  NGrid,
  NIcon,
  useMessage,
} from 'naive-ui';

import {
  genderOptions,
  levelOptions,
  cadreTypeOptions,
  educationOptions,
  degreeOptions,
  teachingDirectionOptions,
} from '@/utils/constants';

import { useUnitStore } from '@/stores/unitStore';
import { useUniversityStore } from '@/stores/universityStore';

const message = useMessage();
const formRef = ref(null);
const isSubmitting = ref(false);

const props = defineProps({
  initialData: {
    type: Object,
    default: () => null
  }
});

const emit = defineEmits(['submit', 'cancel']);

const unitStore = useUnitStore();
const universityStore = useUniversityStore();

// 初始化单位选择器选项
const unitSelectOptions = computed(() => {
  // 优先使用 unitOptions，如果没有则使用 allUnits
  const units = unitStore.unitOptions.length > 0 ? unitStore.unitOptions : unitStore.allUnits;
  return (units || []).map(unit => ({
    label: unit.name,
    value: String(unit._id || unit.id) // 确保value是字符串
  }));
});

// 初始化高校选择器选项
const universitySelectOptions = computed(() => {
  // 优先使用 universityOptions，如果没有则使用 allUniversities
  const universities = universityStore.universityOptions.length > 0 ? universityStore.universityOptions : universityStore.allUniversities;
  return (universities || []).map(uni => ({
    label: uni.schoolName,
    value: String(uni._id || uni.id) // 确保value是字符串
  }));
});

const getDefaultFormValue = () => ({
  name: '',
  gender: null,
  birthDate: null,
  nativePlace: '',
  level: null,
  position: '',
  cadreType: null,
  unitId: null,
  highestEducation: null,
  highestDegree: null,
  expertise: '',
  proposedTeachingDirections: [], // 确保初始值是空数组
  intendedUniversity1: null,
  intendedUniversity2: null,
  intendedUniversity3: null,
  personnelChanges: '',
  remarks: '',
  status: 'active' // 默认状态为在职
});

const formValue = ref(getDefaultFormValue());

// 监听 initialData 变化，用于编辑时填充表单
watch(() => props.initialData, (newData) => {
  if (newData) {
    const dataToSet = { ...getDefaultFormValue(), ...newData };

    // 辅助函数：确保ID是字符串而不是对象
    const ensureStringId = (value) => {
      if (!value) return null;
      if (typeof value === 'string') return value;
      if (typeof value === 'object' && (value._id || value.id)) {
        return value._id || value.id;
      }
      return value;
    };

    // 处理日期格式 - NaiveUI的日期选择器期望时间戳或Date对象
    if (dataToSet.birthDate) {
      if (typeof dataToSet.birthDate === 'string') {
        const parsedDate = new Date(dataToSet.birthDate);
        dataToSet.birthDate = !isNaN(parsedDate.getTime()) ? parsedDate.getTime() : null;
      } else if (dataToSet.birthDate instanceof Date) {
        dataToSet.birthDate = dataToSet.birthDate.getTime();
      } else if (typeof dataToSet.birthDate === 'number') {
        // 已经是时间戳，保持不变
        dataToSet.birthDate = dataToSet.birthDate;
      } else {
        dataToSet.birthDate = null;
      }
    }

    // 确保 proposedTeachingDirections 是数组
    if (!Array.isArray(dataToSet.proposedTeachingDirections)) {
      dataToSet.proposedTeachingDirections = [];
    }

    // 确保所有ID字段都是字符串
    dataToSet.unitId = ensureStringId(dataToSet.unitId);
    dataToSet.intendedUniversity1 = ensureStringId(dataToSet.intendedUniversity1);
    dataToSet.intendedUniversity2 = ensureStringId(dataToSet.intendedUniversity2);
    dataToSet.intendedUniversity3 = ensureStringId(dataToSet.intendedUniversity3);

    console.log('编辑时填充的数据:', dataToSet); // 调试用
    formValue.value = dataToSet;
  } else {
    formValue.value = getDefaultFormValue();
  }
}, { immediate: true, deep: true });

// 表单验证规则
const rules = {
  name: { required: true, message: '请输入姓名', trigger: ['input', 'blur'] },
  gender: { required: true, message: '请选择性别', trigger: ['change', 'blur'] },
  birthDate: {
    required: true,
    message: '请选择出生年月',
    trigger: ['change', 'blur'],
    validator: (rule, value) => {
      if (!value) {
        return new Error('请选择出生年月');
      }
      // 检查是否是有效的时间戳或日期
      if (typeof value === 'number' && !isNaN(value)) {
        // 检查时间戳是否在合理范围内（1900年到2100年）
        const minDate = new Date('1900-01-01').getTime();
        const maxDate = new Date('2100-12-31').getTime();
        if (value >= minDate && value <= maxDate) {
          return true;
        }
        return new Error('请选择有效的出生年月');
      }
      if (value instanceof Date && !isNaN(value.getTime())) {
        return true;
      }
      return new Error('请选择有效的出生年月');
    }
  },
  level: { required: true, message: '请选择级别', trigger: 'change' },
  unitId: { required: true, message: '请选择单位归属', trigger: ['change', 'blur'] },
  cadreType: { required: true, message: '请选择干部类型', trigger: 'change' },
  highestEducation: { required: true, message: '请选择最高学历', trigger: 'change' },
  highestDegree: { required: true, message: '请选择最高学位', trigger: 'change' },
  proposedTeachingDirections: {
    type: 'array',
    validator: (rule, value) => {
      if (!value || value.length === 0) {
        return new Error('请选择拟授课方向');
      }
      if (value.length > 2) {
        return new Error('最多只能选择2个授课方向');
      }
      return true;
    },
    trigger: 'change'
  }
};

const handleCancel = () => {
  emit('cancel');
};

// 重置表单方法，供父组件调用
const resetForm = () => {
  formValue.value = getDefaultFormValue();
  formRef.value?.restoreValidation();
};

// 暴露方法给父组件
defineExpose({
  resetForm
});

// 生成虚拟数据的函数
const generateMockData = () => {
  const surnames = ['张', '王', '李', '赵', '刘', '陈', '杨', '黄', '周', '吴', '徐', '孙', '马', '朱', '胡', '林', '郭', '何', '高', '罗'];
  const maleNames = ['伟', '强', '磊', '军', '勇', '涛', '明', '超', '辉', '华', '建', '峰', '鹏', '志', '杰', '斌', '飞', '刚', '龙', '海'];
  const femaleNames = ['丽', '娜', '敏', '静', '秀', '美', '芳', '燕', '红', '霞', '玲', '梅', '莉', '兰', '英', '萍', '雪', '琴', '慧', '珍'];

  const positions = ['处长', '副处长', '科长', '副科长', '主任', '副主任', '局长', '副局长', '部长', '副部长', '主席', '副主席'];
  const nativePlaces = ['北京市', '上海市', '广东省广州市', '浙江省杭州市', '江苏省南京市', '山东省济南市', '河南省郑州市', '湖北省武汉市', '湖南省长沙市', '四川省成都市'];
  const expertises = ['经济管理', '行政管理', '法律事务', '财务管理', '人力资源', '项目管理', '政策研究', '组织建设', '党建工作', '教育培训'];

  // 随机选择性别
  const genderValue = Math.random() > 0.5 ? '男' : '女';
  const namePool = genderValue === '男' ? maleNames : femaleNames;

  // 生成随机姓名
  const surname = surnames[Math.floor(Math.random() * surnames.length)];
  const name = namePool[Math.floor(Math.random() * namePool.length)];
  const fullName = surname + name;

  // 生成随机出生日期（1960-1990年）
  const birthYear = 1960 + Math.floor(Math.random() * 30);
  const birthMonth = 1 + Math.floor(Math.random() * 12);
  const birthDay = 1 + Math.floor(Math.random() * 28);
  const birthDate = new Date(birthYear, birthMonth - 1, birthDay);

  // 确保生成的日期是有效的时间戳
  const birthTimestamp = birthDate.getTime();
  console.log('生成的出生日期:', birthDate, '时间戳:', birthTimestamp);

  // 随机选择其他字段
  const level = levelOptions[Math.floor(Math.random() * levelOptions.length)].value;
  const cadreType = cadreTypeOptions[Math.floor(Math.random() * cadreTypeOptions.length)].value;
  const education = educationOptions[Math.floor(Math.random() * educationOptions.length)].value;
  const degree = degreeOptions[Math.floor(Math.random() * degreeOptions.length)].value;
  const position = positions[Math.floor(Math.random() * positions.length)];
  const nativePlace = nativePlaces[Math.floor(Math.random() * nativePlaces.length)];
  const expertise = expertises[Math.floor(Math.random() * expertises.length)];

  // 随机选择单位（如果有数据的话）
  const units = unitStore.unitOptions.length > 0 ? unitStore.unitOptions : unitStore.allUnits;
  const unitId = units.length > 0 ? String(units[Math.floor(Math.random() * units.length)]._id || units[Math.floor(Math.random() * units.length)].id) : null;

  // 随机选择高校（如果有数据的话）
  const universities = universityStore.universityOptions.length > 0 ? universityStore.universityOptions : universityStore.allUniversities;
  const getRandomUniversityId = () => {
    if (universities.length === 0) return null;
    return String(universities[Math.floor(Math.random() * universities.length)]._id || universities[Math.floor(Math.random() * universities.length)].id);
  };

  // 随机选择1-2个授课方向
  const shuffledDirections = [...teachingDirectionOptions].sort(() => 0.5 - Math.random());
  const selectedDirections = shuffledDirections.slice(0, 1 + Math.floor(Math.random() * 2));

  // 填充表单数据
  formValue.value = {
    name: fullName,
    gender: genderValue,
    birthDate: birthTimestamp,
    nativePlace: nativePlace,
    level: level,
    position: position,
    cadreType: cadreType,
    unitId: unitId,
    highestEducation: education,
    highestDegree: degree,
    expertise: expertise,
    proposedTeachingDirections: selectedDirections.map(d => d.value),
    intendedUniversity1: getRandomUniversityId(),
    intendedUniversity2: Math.random() > 0.5 ? getRandomUniversityId() : null,
    intendedUniversity3: Math.random() > 0.7 ? getRandomUniversityId() : null,
    personnelChanges: '',
    remarks: `这是${fullName}的虚拟测试数据`,
    status: 'active'
  };


};

const handleValidateAndSubmit = async () => {
  if (isSubmitting.value) return; // 防止重复提交

  try {
    isSubmitting.value = true;
    await formRef.value?.validate();

    // 辅助函数：确保ID是字符串而不是对象
    const ensureStringId = (value) => {
      console.log('ensureStringId 输入:', value, '类型:', typeof value);
      if (!value) return null;
      if (typeof value === 'string') return value;
      if (typeof value === 'object' && (value._id || value.id)) {
        const result = value._id || value.id;
        console.log('从对象中提取ID:', result);
        return result;
      }
      return value;
    };

    console.log('表单原始数据:', formValue.value);

    // 确保提交的数据中所有ID字段都是字符串
    const submitData = {
      ...formValue.value,
      proposedTeachingDirections: Array.isArray(formValue.value.proposedTeachingDirections)
        ? formValue.value.proposedTeachingDirections
        : [],
      // 确保日期格式正确 - 转换为ISO字符串
      birthDate: formValue.value.birthDate ? (() => {
        try {
          const date = new Date(formValue.value.birthDate);
          if (isNaN(date.getTime())) {
            console.warn('无效的日期值:', formValue.value.birthDate);
            return null;
          }
          return date.toISOString();
        } catch (error) {
          console.error('日期转换失败:', error);
          return null;
        }
      })() : null,
      // 确保所有ID字段都是字符串
      unitId: ensureStringId(formValue.value.unitId),
      intendedUniversity1: ensureStringId(formValue.value.intendedUniversity1),
      intendedUniversity2: ensureStringId(formValue.value.intendedUniversity2),
      intendedUniversity3: ensureStringId(formValue.value.intendedUniversity3)
    };

    console.log('提交的数据:', submitData); // 调试用
    await emit('submit', submitData);
  } catch (error) {
    console.error('表单验证失败:', error);
    message.error('请检查表单填写是否正确');
  } finally {
    isSubmitting.value = false;
  }
};

// 组件挂载时加载数据
onMounted(async () => {
  try {
    await Promise.all([
      unitStore.fetchUnitOptions(),
      universityStore.fetchUniversityOptions()
    ]);
  } catch (error) {
    message.error('加载数据失败：' + error.message);
  }
});
</script>

<style scoped>
.w-full {
  width: 100%;
}
</style>